﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using SimpleNotify.ClientLibrary.NotifyService;
using System.ServiceModel;
using System.Threading;
using System.Drawing;

namespace SimpleNotify.ClientLibrary
{
    public class Client : IServiceCallback
    {
        private BackgroundWorker _keepAliveWorker = null;
        private ServiceClient _notifyService = null;
        private bool _connected = false;
        private string _notifyServer = String.Empty;
        private System.ServiceModel.InstanceContext _instanceContext = null;

        public event EventHandler<ConnectionChangedEventArgs> OnConnectionChanged;
        public event EventHandler<NewNotificationEventArgs> OnNotificationReceived;

        public Client(string notifyServer)
        {
            _instanceContext = new InstanceContext(this);

            _notifyServer = notifyServer;
            CreateProxy();

            _keepAliveWorker = new BackgroundWorker();
            _keepAliveWorker.WorkerSupportsCancellation = true;
            _keepAliveWorker.DoWork += new DoWorkEventHandler(_keepAliveWorker_DoWork);
            _keepAliveWorker.RunWorkerAsync();
        }

        private void CreateProxy()
        {
            string endpointAddress = String.Format("http://{0}:80/Service.svc", _notifyServer);

            WSDualHttpBinding binding = new WSDualHttpBinding(WSDualHttpSecurityMode.None);
            binding.OpenTimeout = new TimeSpan(0, 0, 30);
            binding.CloseTimeout = new TimeSpan(0, 0, 30);
            binding.ReceiveTimeout = new TimeSpan(0, 5, 0);
            binding.CloseTimeout = new TimeSpan(0, 0, 30);
            _notifyService = new ServiceClient(_instanceContext, binding, new EndpointAddress(endpointAddress));
            _notifyService.InnerDuplexChannel.Faulted += new EventHandler(InnerDuplexChannel_Faulted);
        }

        void InnerDuplexChannel_Faulted(object sender, EventArgs e)
        {

        }

        private void _keepAliveWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!_keepAliveWorker.CancellationPending)
            {
                CheckAndRefreshConnection();
                Thread.Sleep(20000);
            }
        }

        private void CheckAndRefreshConnection()
        {
            bool oldConnectedState = _connected;

            try
            {
                // If channel was closed earlier, we try to open again
                if (_notifyService.State == CommunicationState.Closed || _notifyService.State == CommunicationState.Faulted)
                {
                    CreateProxy();
                }

                _connected = _notifyService.Subscribe(Environment.MachineName.ToUpper());
            }
            catch (TimeoutException)
            {
                _connected = false;
                // Create a new proxy for next attempt
                CreateProxy();
            }
            catch (Exception)
            {
                _connected = false;
            }

            if (oldConnectedState != _connected)
            {
                if (OnConnectionChanged != null)
                {
                    OnConnectionChanged(this, new ConnectionChangedEventArgs(_connected));
                }
            }
        }

        public bool Notify(string title, string text, NotifyService.NotificationType Type, string data)
        {
            if (OnNotificationReceived != null)
            {
                NotificationType type = TranslateTypeToType(Type);
                OnNotificationReceived(this, new NewNotificationEventArgs() { Title = title, Text = text, Type = type, Data = data});
            }
            return true;
        }

        private NotificationType TranslateTypeToType(NotifyService.NotificationType fromType)
        {
            NotificationType toType = NotificationType.None;
            switch (fromType)
            {
                case SimpleNotify.ClientLibrary.NotifyService.NotificationType.Information:
                    toType = NotificationType.Information;
                    break;
                case SimpleNotify.ClientLibrary.NotifyService.NotificationType.Warning:
                    toType = NotificationType.Warning;
                    break;
                case SimpleNotify.ClientLibrary.NotifyService.NotificationType.Error:
                    toType = NotificationType.Error;
                    break;
                case SimpleNotify.ClientLibrary.NotifyService.NotificationType.Confirmation:
                    toType = NotificationType.Confirmation;
                    break;
            }
            return toType;
        }

        public bool IsConnected
        {
            get
            {
                return _connected;
            }
        }
    }
}
